wpf 通过InvokeCommandAction来绑定Command | 您所在的位置:网站首页 › wpf cmd异步 › wpf 通过InvokeCommandAction来绑定Command |
1 新建wpf程序,通过nuget添加Microsoft.Xaml.Behaviors库 2 创建Base ViewModels文件夹 3 在Base里面创建CommandBase类 using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; namespace WpfApp3.Base { public class CommandBase : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { DoExecute?.Invoke(parameter); } public Action DoExecute; } }4 在ViewModels里面创建MainViewModel类 using System; using System.Collections.Generic; using System.Text; using WpfApp3.Base; namespace WpfApp3.ViewModels { public class MainViewModel { public CommandBase TestCommand { get; set; } public MainViewModel() { TestCommand = new CommandBase(); TestCommand.DoExecute = new Action(DoAction); } private void DoAction(object obj) { } } }5 修改MainWindow using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using WpfApp3.ViewModels; namespace WpfApp3 { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainViewModel(); } } }6 运行 注意,该方法没有用CallMethodAction方法直接,这种还要建Command,但不用像CallMethodAction方法那样将事件从view拷贝到viewmodel |
CopyRight 2018-2019 实验室设备网 版权所有 |